/* eslint-disable no-nested-ternary */
import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { exportQAHistories } from '@/services/download';
import qs from 'qs';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import { Card, Row, Col, Form, Input, Button, message, Icon, Checkbox, Table, Tag, Select, Modal, Radio, Spin, Upload } from "antd";
import download from '@/utils/download';


const FormItem = Form.Item;
const Search = Input.Search;
const InputGroup = Input.Group;
import styles from "./index.less";
import { faTshirt } from '@fortawesome/fontawesome-free-solid';
const { Option } = Select;
const { TextArea } = Input;
const RadioGroup = Radio.Group;
import pen from '../../../assets/icons/bi.png';
import ljx from '../../../assets/icons/垃圾箱.png';
const MyIcon = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1131883_m18hmgbwet.js', // 在 iconfont.cn 上生成
});


class CustomDictionary extends Component {
  state = {
    total: 0,
    totab: '',
    disabled: true,
    dataSource1: [],
    pageSize: 10,
    page: 1,
    pageSizeA: 10,
    pageA: 1,
    Accord: '1',
    formatA: '',
    formatB: '',
    formatC: '',
    listday: [],
    showModel1: false,
    showModel2: false,
    tota2: 1,
    itemId: '',
    login: false,
    tcxModel: false,
    uploadId: {},
    dictItemNames: '',
    mockValue: '',
    ziyevalue: '',
    fileList:[]
  };


  // eslint-disable-next-line react/sort-comp
  fetch = (dictType, page, limit, dictNames) => {
    this.setState({
      login: true
    })
    const { dispatch, currentUser } = this.props;
    let temp = [...this.state.dataSource1]

    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'customDictionary/fetch',
        payload: { robotId: currentUser.robotId, dictType, page, limit, dictNames },
        callback: res => {

          let temp = res.list
          // temp.reverse()
          temp.map((item, index) => {
            item['key'] = index
          })
          this.setState({
            dataSource1: temp,
            total: res.total,
            login: false
          })
        },
      });
    });
    this.props.form.setFields({ "corewordone": "" })
  }


  fetchb = (dictId, page, limit, itemNames) => {
    this.setState({
      login: true,
      dataSource2: [],
      listday: [],
    })
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'customDictionary/fetchb',
        payload: { dictId, page, limit, itemNames },
        callback: res => {

          let a = res.list
          a.map((item, index) => {
            item['key'] = index
          })
          this.setState({
            dataSource2: a,
            listday: a,
            totab: res.total,

          })
          setTimeout(() => {
            this.setState({
              login: false
            })
          }, 500)
        },
      });
    });
  }

  componentDidMount() {
    // 首页
    this.fetch()
    // const { dispatch, currentUser } = this.props;
    //
    // 可枚举页一开始数据
    // this.fetchb()
  }

  businessWayA = () => {
    this.setState({ tcxModel: false })
    // message.success('ok')
    this.setState({ fileList:[] });
    this.fetchb(this.state.okid, this.state.pageA, this.state.pageSizeA, this.state.ziyevalue)
  }

  //
  handleDelete = (item) => {

    let uploadId = {}
    uploadId.dictId = item._id
    this.setState({
      okid: item._id,
      okname: item.name,
      uploadId,
    })
    // this.fetchb(item._id, 1, 10, '')
    this.fetchb(item._id, this.state.pageA, this.state.pageSizeA, this.state.ziyevalue)

    if (item.isEnum) { // 可枚举
      this.setState({
        Accord: '2'
      })
    }
    if (item.isEnum === false) { // 不可枚举
      this.setState({
        Accord: '3'
      })
    }
  }

  //
  handleDeleteA = (item) => {

    this.setState({
      formatA: item.word,
      formatB: item.synWords.join(','),
      itemId: item._id,
      showModel2: true
    })
  }

  handleDeletes = (item) => {

    Modal['confirm']({
      title: '删除任务',
      content: '确定删除吗？',
      okText: "删除",
      cancelText: "取消",
      onOk: () => {
        const { dispatch, currentUser } = this.props;
        this.reqRef = requestAnimationFrame(() => {
          dispatch({
            type: 'customDictionary/fetchd',
            payload: { dictId: item._id },
            callback: res => {

              if (res.status) {
                message.success(`${res.msg}`)
              }
              this.fetch('', this.state.page, this.state.pageSize, this.state.dictItemNames)
            },
          });
        });
      },
      onCancel() {

      }
    })
  }

  fromDeletes = (item) => {

    Modal['confirm']({
      title: '删除任务',
      content: '确定删除吗？',
      okText: "删除",
      cancelText: "取消",
      onOk: () => {
        const { dispatch } = this.props;
        this.reqRef = requestAnimationFrame(() => {
          dispatch({
            type: 'customDictionary/fetchg',
            payload: { dictId: this.state.okid, dictItemId: item._id },
            callback: res => {

              // this.fetchb(this.state.okid, 1, 10, '')
              this.fetchb(this.state.okid, this.state.pageA, this.state.pageSizeA, this.state.ziyevalue)
              if (res.status) {
                message.success(`执行成功！`)
              }

            },
          });
        });
      },
      onCancel() {

      }
    })

  }

  // eslint-disable-next-line react/sort-comp
  onChangeA = (val) => { // 页数选择

    this.setState({
      page: val
    })
    this.fetch('', val, this.state.pageSize, this.state.dictItemNames)
  }

  // 每页显示多少条数据
  onShowSizeChangeA = (current, pageSize) => {

    this.setState({
      page: current,
      pageSize: pageSize
    })
    this.fetch('', current, pageSize, this.state.dictItemNames)

  }

  // eslint-disable-next-line react/sort-comp
  onChangeB = (val) => { // 页数选择

    this.setState({ pageA: val }, () => {
      this.fetchb(this.state.okid, this.state.pageA, this.state.pageSizeA, this.state.ziyevalue)
    })
    // this.fetchb(this.state.okid, val, '', '')
  }

  // 每页显示多少条数据
  onShowSizeChangeB = (current, pageSize) => {

    this.setState({ pageA: current, pageSizeA: pageSize }, () => {
      this.fetchb(this.state.okid, this.state.pageA, this.state.pageSizeA, this.state.ziyevalue)
    })
    // this.fetchb(this.state.okid, current, pageSize, '')
  }

  // 字典名称显示或隐藏
  modifyClick = () => {
    this.setState({
      disabled: false
    })

  }

  toLeadt = () => {
    this.setState({ tcxModel: true })
  }

  // 导出
  answerDetail = () => {
   if(this.state.totab===0){
     message.error('空列表无法导出！')
   }else{
    const {dispatch,currentUser} = this.props;
    const { ziyevalue, uploadId } = this.state
    let up = uploadId.dictId
    let object = {};

    object.robotId = currentUser.robotId;
    object.dictId = up;
    object.dictItemNames = ziyevalue;
    dispatch({
      type: 'customDictionary/exporta',
      payload: object,
      callback:(res)=>{
        let filename = decodeURIComponent(res.requestRes.headers.get('Content-Disposition').split('=')[1]);
        download.byBlob(res.fileBlob,filename)
      }
    });
   }

  }

  // 下载模版
  dictTemp =()=>{
    // window.open('/basic/dict/import/template?')
    const {dispatch,currentUser} = this.props;
    dispatch({
      type: 'customDictionary/templateA',
      payload:{},
      callback:(res)=>{
        let filename = decodeURIComponent(res.requestRes.headers.get('Content-Disposition').split('=')[1]);
        download.byBlob(res.fileBlob,filename)
      }
    });
  }

  namegai = (e) => {

    this.setState({ mockValue: e.target.value })
  }

  bcClick = () => {
    if (this.state.mockValue === '') {
      // message['warning']('未修改')

      this.setState({
        disabled: true
      })

      const { dispatch } = this.props;
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: 'customDictionary/fetche',
          payload: { dictId: this.state.okid, dictName: this.state.okname },
          callback: res => {

            if (res.status === true) {
              message['success'](`${res.msg}`)
            }
            if (res.status === false) {
              message['error'](`${res.msg}`)
            }
            // this.fetch('',ths.state.page,this.state.pageSize,'')
            this.fetch('', this.state.page, this.state.pageSize, this.state.dictItemNames)

          },
        });
      });
    } else {
      this.setState({
        disabled: true
      })
      // message['success']('修改成功')
      // 可枚举页 修改词典

      const { dispatch } = this.props;
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: 'customDictionary/fetche',
          payload: { dictId: this.state.okid, dictName: this.state.mockValue },
          callback: res => {

            if (res.status === true) {
              message['success'](`${res.msg}`)
            }
            if (res.status === false) {
              message['error'](`${res.msg}`)
            }
            // this.fetch('',ths.state.page,this.state.pageSize,'')
            this.fetch('', this.state.page, this.state.pageSize, this.state.dictItemNames)

          },
        });
      });
    }
  }

  textInput = () => {
    const { getFieldDecorator } = this.props.form;
    return (
      <div className={styles.flexcen}>
        <Form layout="inline" onSubmit={this.handleSubmit}>
          <FormItem label='词典名称'>
            {getFieldDecorator('namecid', {
              initialValue: '',
            })(
              <div >
                <Input
                  defaultValue={this.state.okname}
                  disabled={this.state.disabled}
                  onPressEnter={this.saveChanges}
                  onChange={this.namegai}
                />
              </div>

            )}


          </FormItem>
          {this.state.disabled === true ? <span><Icon onClick={this.modifyClick} className={styles.fleximg} type="edit" /></span> : <span><Icon onClick={this.bcClick} className={styles.fleximg} type="check" /></span>}

        </Form>
      </div>
    )
  }

  lessdata = () => {
    const columns = [
      {
        title: <FormattedMessage id="app.customDictionary.dictionary-list" defaultMessage="dictionaryList" />,
        width: 'calc(30vw)',
        dataIndex: 'name'//返回的索引值
      },
      {
        title: <FormattedMessage id="app.customDictionary.dictionary-types" defaultMessage="dictionaryTypes" />,
        width: 'calc(30vw)',
        dataIndex: 'isEnum',
        render(sex) {
          return sex === true ? '可枚举类型' : '不可枚举类型'
        }
      },
      {
        title: <FormattedMessage id="app.customDictionary.operation" defaultMessage="operation" />,
        dataIndex: 'sex',
        render: (text, item) => {
          return <div className={styles.pb}>
            <div
              className={styles.buttongl}
              onClick={(text) => { this.handleDelete(item) }}>
              <img style={{ marginRight: 5 }} src={pen} />
              <FormattedMessage id="app.customDictionary.edit" defaultMessage="Edit" />
            </div>
            <div
              style={{ marginLeft: 10, background: '#e8313b' }}
              className={styles.buttongl}
              onClick={(text) => { this.handleDeletes(item) }}>
              <span><Icon size="small" type="delete" style={{ marginRight: 5 }} />
              </span><span> <FormattedMessage id="app.customDictionary.out" defaultMessage="out" /></span>
            </div>
          </div>
        }
      }
    ]
    const columns1 = [
      {
        title: <FormattedMessage id="app.customDictionary.core-word" defaultMessage="coreWord" />,
        width: 'calc(30vw)',
        dataIndex: 'word'
      },
      {
        title: <FormattedMessage id="app.customDictionary.core-agreed" defaultMessage="agreed" />,
        width: 'calc(30vw)',
        dataIndex: 'synWords',
        render: synWords => (
          <span>
            {synWords.map((tag, index) => {
              let color = index % 2 == 1 ? '#5092e1' : '#87d3ac';
              return <Tag style={{ marginBottom: 2 }} color={color} key={tag}>{tag}</Tag>;
            })}
          </span>
        ),
      },
      {
        title: <FormattedMessage id="app.customDictionary.operation" defaultMessage="operation" />,
        dataIndex: 'sex',
        render: (text, item) => {
          return <div className={styles.pb}>
            <div
              className={styles.buttongl}
              onClick={(text) => { this.handleDeleteA(item) }}>
              <img style={{ marginRight: 5 }} src={pen} />
              <FormattedMessage id="app.customDictionary.edit" defaultMessage="Edit" />
            </div>
            <div
              style={{ marginLeft: 10, background: '#e8313b' }}
              className={styles.buttongl}
              onClick={(text) => { this.fromDeletes(item) }}>
              <span><Icon size="small" type="delete" style={{ marginRight: 5 }} /></span>
              <span> <FormattedMessage id="app.customDictionary.out" defaultMessage="out" /></span>
            </div>
          </div>
        }
      }
    ]
    if (this.state.Accord === '1') {
      return ( //主页
        <Spin spinning={this.state.login}>
          <Table
            style={{ padding: '0px 30px 0px 30px' }}
            columns={columns}
            dataSource={this.state.dataSource1}//数据
            onChange={this.handleChange}
            pagination={{  // 分页
              total: this.state.total,
              pageSize: this.state.pageSize,  // 显示几条一页
              current: this.state.page, // 当前页
              showSizeChanger: true,  // 是否显示可以设置几条一页的选项
              showQuickJumper: true,
              onChange: this.onChangeA,
              onShowSizeChange: this.onShowSizeChangeA
            }}

          />
        </Spin>
      )
    }
    if (this.state.Accord === '2') {
      return (
        <Spin spinning={this.state.login}>
          <Table // 可枚举类型
            style={{ padding: '0px 30px 0px 30px' }}
            columns={columns1}
            dataSource={this.state.dataSource2}// 数据
            onChange={this.handleChange}
            pagination={{  // 分页
              total: this.state.totab,
              pageSize: this.state.pageSizeA,  // 显示几条一页
              current: this.state.pageA, // 当前页
              showSizeChanger: true,  // 是否显示可以设置几条一页的选项
              showQuickJumper: true,
              onChange: this.onChangeB,
              onShowSizeChange: this.onShowSizeChangeB
            }}

          />
        </Spin>
      )
    }
  }

  returnButton = () => {
    if (this.state.Accord === '2' || this.state.Accord === '3') {
      return <span onClick={this.returnHome} className={styles.bs} style={{ float: 'right', width: 50 }}>返回</span>
    }
  }

  returnHome = () => {
    this.setState({
      Accord: '1',
      editorA: false,
      mockValue: ''
    })
  }

  handleChangeByUpload = info =>{

    let fileList = [...info.fileList];
    fileList = fileList.slice(-1);

    fileList = fileList.map(file => {
      if (file.response) {
       if(file.response.code){
         message.error(file.response.msg)
       }else{
         file.url = file.response.url;
       }
      }
      return file;
    });
    this.setState({ fileList });
  }

  // eslint-disable-next-line react/sort-comp  JSON.parse(window.localStorage.getItem("currentUser")).token
  render() {
    const headData = {"token":JSON.parse(window.localStorage.getItem("currentUser")).token};
    const props = {
      name: 'file',
      headers:headData,
      data: this.state.uploadId,
      action: '/basic/dict/import',
      accept: '.xlsx,.xls',
      onChange: this.handleChangeByUpload,
    }
    const { getFieldDecorator } = this.props.form;
    const FormItemLayont = {
      labelCol: {// 文字
        xs: 24,
        sm: 4
      },
      wrapperCol: {// 输入框
        xs: 24,
        sm: 20
      }
    }
    return (
      <Suspense fallback={<PageLoading />}>
        <PageHeaderWrapper>
          <div className={styles.backgroundp}>

            <Row className={styles.colorBackground}>
              <Col style={{ padding: 10, }} xs={24} className={styles.colorA}>
                <span className={styles.title}>
                  <span>词典详情{`(${this.state.total})`}</span>
                </span>
                {this.returnButton()}
              </Col>
            </Row>
            {this.state.Accord === '1' ? '' : this.textInput()}
            <Card
              bordered={false}
            >


              {
                this.state.Accord === '3' ? '' :
                  this.state.Accord === '1' ?
                    <div className={styles.fromColumn}>
                      <Button icon="plus" onClick={this.addContent}><FormattedMessage id="app.customDictionary.add" defaultMessage="add" /></Button>
                      <span className={styles.right}>
                        <Search
                          placeholder="请输入搜索内容"
                          onSearch={value => {

                            this.setState({ dictItemNames: value, page: 1 }, () => {
                              this.fetch('', this.state.page, this.state.pageSize, value)
                            })

                          }}
                          style={{ width: 323 }}
                        />
                      </span>
                    </div>
                    :
                    <div className={styles.fromColumn}>
                      <Button onClick={this.enumeration} icon="plus"><FormattedMessage id="app.customDictionary.add" defaultMessage="add" /></Button>
                      <Button onClick={this.toLeadt}>导入</Button>
                      <Button onClick={this.answerDetail}>导出</Button>
                      <span className={styles.right}>
                        <Search
                          placeholder="请输入搜索内容"
                          onSearch={value => {

                            this.setState({ ziyevalue: value, pageA: 1 }, () => {
                              // this.fetchb(this.state.okid, 1, 10, value)
                              this.fetchb(this.state.okid, this.state.pageA, this.state.pageSizeA, this.state.ziyevalue)
                            })

                          }}
                          style={{ width: 323 }}
                        />
                      </span>
                    </div>
              }

              {
                this.lessdata()
              }

              {this.state.Accord === '1' || this.state.Accord === '2' ? '' : <Button style={{ marginBottom: 18 }} type="primary" onClick={this.handleSubmitC} icon="plus"><FormattedMessage id="app.customDictionary.add-new-format" defaultMessage="Rank" /></Button>}


              {this.state.Accord === '1' || this.state.Accord === '2' ? '' : this.state.listday.map((item, index) => {

                return (
                  <Spin spinning={this.state.login}>
                    <Form layout="inline" style={{ marginBottom: 10 }}>
                      <FormItem>
                        <Select style={{ width: 160 }} defaultValue={item.word === '' ? 'regex' : item.word} onChange={e => this.busChanges(e, index)}>
                          <Option value='regex'>
                          <FormattedMessage id="app.customDictionary.regular-expression" defaultMessage="Regular expression" />
                          </Option>
                          <Option value='placeholder'>
                          <FormattedMessage id="app.customDictionary.placeholder" defaultMessage="placeholder" />
                          </Option>
                        </Select>
                      </FormItem>
                      <FormItem>
                        <Input style={{ width: 354 }} value={item.synWords[0]} onChange={e => this.busChange(e, index)}></Input>
                      </FormItem>
                      <FormItem>
                        <span><img src={ljx} onClick={() => this.handleSubmitA(index)} /></span>
                      </FormItem>
                    </Form>
                  </Spin>

                );
              })}
              {this.state.Accord === '1' || this.state.Accord === '2' ? '' : <div><Button style={{ background: '#19c3f3', color: '#ffffff', marginTop: 18 }} onClick={this.handleSubmitB}>保存</Button></div>}

              {this.state.Accord === '1' || this.state.Accord === '2' ? '' : <div className={styles.textOne}>
                <div style={{ padding: '20px 30px 40px 30px' }}>
                  <h5 style={{ fontWeight: 'bold' }}><FormattedMessage id="app.customDictionary.enumeration-texta" /></h5>
                  <p><FormattedMessage id="app.customDictionary.enumeration-textb" /></p>
                  <p><FormattedMessage id="app.customDictionary.enumeration-textc" /></p>
                  <p>{'可用 ？代表单个数字/字母，* 代表任意多个(>=1)数字/字母'}</p>
                  <h5 style={{ fontWeight: 'bold' }}><FormattedMessage id="app.customDictionary.enumeration-textd" /></h5>
                  <p>按照标准的正则表达式语法编写即可，具体语法可参考：正则表达式介绍</p>
                  <p style={{ lineHeight: 2 }}><span style={{ fontWeight: 700 }}>注:</span>此处的正则表达式不支持使用大写字母。(因为对于用户输入的内容，系统会先将其中的大写字母都转换成小写，然后再进行识别抽取，因此如果用大写字母的话会造成系统无法识别。)</p>

                </div>
              </div>
              }
            </Card>

            <Modal
              title={<FormattedMessage id="app.customDictionary.add-dictionary" />}
              visible={this.state.showModel1}
              okText={<FormattedMessage id="app.customDictionary.save" />}
              cancelText={<FormattedMessage id="app.customDictionary.cancel" />}

              onCancel={() => {
                this.props.form.setFields({ "corewordone": "" })
                this.setState({
                  showModel1: false
                })
              }}
              onOk={this.coreWordOne}// 确定方法开出去
            >
              <Form layout="horizontal">
                <FormItem label='词典名称' onSubmit={this.coreWordOne} {...FormItemLayont}>
                  {getFieldDecorator('corewordone', {
                    initialValue: `${this.state.formatC}`,
                  })(
                    <Input />
                  )}

                </FormItem>
                <FormItem label='词典类型' {...FormItemLayont}>
                  {getFieldDecorator('dictionaryTypes', {
                    initialValue: '1',
                  })(
                    <RadioGroup>
                      <div className={styles.newline}>
                        <Radio value='1'><FormattedMessage id="app.customDictionary.enumerable-type" /></Radio>
                        <span style={{ color: '#cccccc' }}><FormattedMessage id="app.customDictionary.enumerable-typetext" /></span>
                        <Radio value='2'><FormattedMessage id="app.customDictionary.noenumerable-type" /></Radio>
                        <span style={{ color: '#cccccc' }}><FormattedMessage id="app.customDictionary.noenumerable-typetext" /></span>
                      </div>

                    </RadioGroup>
                  )}
                </FormItem>
              </Form>
            </Modal>

            <Modal
              title={<FormattedMessage id="app.customDictionary.add-compiler-dictionary" />}
              visible={this.state.showModel2}
              okText={<FormattedMessage id="app.customDictionary.save" />}
              cancelText={<FormattedMessage id="app.customDictionary.cancel" />}

              onCancel={() => {
                this.setState({
                  showModel2: false
                })
              }}
              onOk={this.coreWord}// 确定方法开出去
            >
              <Form layout="horizontal">
                <FormItem label={<FormattedMessage id="app.customDictionary.core-word" />} onSubmit={this.coreWord} {...FormItemLayont}>
                  {getFieldDecorator('coreword', {
                    initialValue: `${this.state.formatA}`,
                  })(
                    <Input />
                  )}

                </FormItem>
                <FormItem label={<FormattedMessage id="app.customDictionary.core-agreed" />} {...FormItemLayont}>
                  {getFieldDecorator('synonym', {
                    initialValue: `${this.state.formatB}`,
                  })(
                    <TextArea
                      placeholder="请输入同义词名称，可填写多个，请以中英文逗号分隔"
                      autosize={
                        {
                          minRows: 4, maxRows: 6
                        }
                      }
                    />
                  )}
                </FormItem>
              </Form>
            </Modal>

            <Modal
              width={550}
              title='上传词典'
              visible={this.state.tcxModel}
              okText={<FormattedMessage id="app.customDictionary.save" />}
              cancelText={<FormattedMessage id="app.customDictionary.cancel" />}
              onCancel={() => {
                this.setState({ tcxModel: false })
                this.setState({ fileList:[] });
              }}
              onOk={this.businessWayA}// 确定方法开出去
            >
              <Form layout="horizontal">
                <FormItem label='选择文件'  {...FormItemLayont}>
                  <Upload {...props}  fileList={this.state.fileList} >
                    <Button >
                      <Icon type="upload" /> 选择文件
                    </Button>
                  </Upload>
                </FormItem>
                <FormItem label='上传规则'  {...FormItemLayont}>
                  <div className={styles.frame}>
                    <div><span>• 请按照模板中的示例格式进行编辑上传：</span> <span onClick={this.dictTemp} className={styles.template}>下载xlsx模版</span></div>
                    <div><span>•上传文件格式需要为“.xlsx”类型的Excel文件</span></div>
                    <div><span>• 导入的词典数据将覆盖现有数据，请谨慎操作</span></div>
                  </div>
                </FormItem>
              </Form>
            </Modal>
          </div>

        </PageHeaderWrapper>
      </Suspense>
    );
  }

  // 新增
  handleSubmitC = () => {
    let arr = this.state.listday
    let dictItems = {
      word: 'regex',
      synWords: [],
    }
    arr.push(dictItems)

    this.setState({
      listday: arr
    })
  }

  //删除
  handleSubmitA = (index) => {

    let arr = this.state.listday
    arr.splice(index, 1)

    this.setState({
      listday: arr
    })



  }

  busChange = (e, index) => {

    let arr = this.state.listday
    arr[index].synWords = []
    arr[index].synWords.push(e.target.value)
    this.setState({
      listday: arr
    })

  }

  busChanges = (value, index) => {

    let arr = this.state.listday
    arr[index].word = value

  }


  handleSubmitB = () => {
    const { dispatch } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'customDictionary/fetchh',
        payload: { dictId: this.state.okid, dictItems: this.state.listday },
        callback: res => {

          if (res.status === true) {
            message['success'](`${res.msg}`)
          }
          if (res.status === false) {
            message['error'](`${res.msg}`)
          }
          // this.fetch()
          this.fetch('', this.state.page, this.state.pageSize, this.state.dictItemNames)

        },
      });
    });
  }

  // 主页增加
  coreWordOne = () => {
    let userInfo = this.props.form.getFieldsValue();// 获取数据
    this.props.form.validateFields((err, values) => {// 校验方法
      let userInfo = this.props.form.getFieldsValue();// 获取数据
      if (!err) {

        let obj;
        if (userInfo.dictionaryTypes === '1') {
          obj = true
        }
        if (userInfo.dictionaryTypes === '2') {
          obj = false
        }
        const { dispatch, currentUser } = this.props;
        this.reqRef = requestAnimationFrame(() => {
          dispatch({
            type: 'customDictionary/fetchc',
            payload: { dictName: userInfo.corewordone, isEnum: obj },
            callback: res => {

              if (res.code === 0) {
                message['success'](`${res.msg}`)
                this.setState({
                  showModel1: false,
                  formatC: ''
                })
                this.fetch()
              }
              if (res.status === false) {
                // message['error'](`${res.msg}`)
              }
            },
          });
        });
      }
    })

    // this.props.form.setFields({ "synonym": "" })
  }



  // 子页面
  coreWord = () => {
    let userInfo = this.props.form.getFieldsValue();// 获取数据
    this.props.form.validateFields((err, values) => {// 校验方法
      let userInfo = this.props.form.getFieldsValue();// 获取数据

      if (!err) {


        if (userInfo.coreword !== '') {
          const { dispatch, currentUser } = this.props;
          this.reqRef = requestAnimationFrame(() => {
            dispatch({
              type: 'customDictionary/fetchf',
              payload: { dictId: this.state.okid, itemWord: userInfo.coreword, itemSynWords: userInfo.synonym, itemId: this.state.itemId },
              callback: res => {



                // this.fetchb(this.state.okid, 1, 10, '')


                if (res.status) {
                  message.success(`${res.msg}`)
                  this.setState({
                    showModel2: false,
                    pageA: 1
                  }, () => {
                    this.fetchb(this.state.okid, this.state.pageA, this.state.pageSizeA, this.state.ziyevalue)
                  })
                } else {
                  this.setState({
                    showModel2: true
                  })
                }

              },
            });
          });
        } else {
          message['warning']('请添加核心词')
        }

      }
    })
  }

  // 主页添加内容
  addContent = () => {
    this.setState({
      showModel1: true
    })
  }

  // 子页面修改内容
  enumeration = () => {
    this.props.form.setFields({ "coreword": "" })
    this.props.form.setFields({ "synonym": "" })
    this.setState({
      formatA: '',
      formatB: '',
      showModel2: true,
      itemId: ''
    })
  }

  addContentA = () => {

  }
}

export default connect(({ user }) => ({ // 全局数据
  currentUser: user.currentUser,
}))(Form.create()(CustomDictionary));
